import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Menu } from 'src/entity/Menu'
import { Connection, IsNull, Repository } from 'typeorm'
import { BusinessException } from './../common/exceptions/business.exception'
import { Role } from 'src/entity/Role'
import { RoleService } from 'src/role/role.service'

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu)
    private menuRepository: Repository<Menu>,
    private readonly roleService: RoleService,
    private connection: Connection,
  ) { }

  async add(data: {
    funcName: string
    // funcPerms: string
    url: string | null
    funcType: number
    parentId: number
    sortOrder: number
    funcIcon: string | null
    compName: string
    compPath: string
    routeQuery: string | null
    isCache: boolean
    isDisplay: boolean
  }): Promise<Menu> {
    const isExist = await this.menuRepository.findOne({
      where: {
        funcName: data.funcName,
      },
    })
    if (isExist) throw new BusinessException('菜单已经存在')

    const menu = new Menu()
    Object.keys(data).forEach((key) => {
      menu[key] = data[key] !== null ? data[key] : null
    })
    const sqlData = await this.menuRepository.save(menu)
    return sqlData
  }

  // 获取菜单
  async getMenu(roleCode: string, isAllMenu: boolean) {
    let menuIdsList
    // 获取所有菜单
    if (isAllMenu) {
      menuIdsList = []
    } else {
      // 获取角色菜单
      menuIdsList = await this.roleService.getMenuBYRoleCode(roleCode)
    }
    const menuSqlData = await this.menuRepository.find({
      where: menuIdsList.length
        ? menuIdsList.map((item) => {
          return {
            id: item,
            isDelete: IsNull(),
          }
        })
        : { isDelete: IsNull() },
    })
    return translateToMenuTree(menuSqlData, 0)

    function translateToMenuTree(menuList: any[], parentId) {
      const temMenuList = menuList.filter((item) => item.parentId === parentId)
      temMenuList.forEach((item, index) => {
        temMenuList[index].children =
          translateToMenuTree(
            menuList.filter((item) => item.parentId !== parentId) || [],
            item.id,
          ) || null
      })
      return temMenuList?.length
        ? // 根据sortOrder升序排序
        temMenuList.sort((pre, next) => {
          return pre.sortOrder - next.sortOrder
        })
        : null
    }
  }

  // 菜单列表查询
  async getPageList() {
    const sqlAllData = await this.menuRepository.find({
      where: {
        isDelete: IsNull(),
      },
    })
    return {
      content: sqlAllData,
      total: sqlAllData.length,
    }
  }

  // 更新
  async update(data) {
    delete data.children
    await this.menuRepository.update(
      {
        id: data.id,
      },
      data,
    )
    return {}
  }

  // 删除菜单
  async del(id) {
    // 查询是否存在下级资源
    const find = await this.menuRepository.findOne({
      where: {
        parentId: id,
        isDelete: IsNull(),
      },
    })
    // 存在，不能删除菜单
    if (find) {
      throw new BusinessException(
        '该菜单存在下级资源，无法删除，请删除下级资源后再次尝试',
      )
    }
    await this.menuRepository.update(
      {
        id: id,
      },
      {
        isDelete: true,
      },
    )
  }
}
